var comPageNum = 1;//分页公共页码
var financeHasData = false;//是否存在财务信息
var financeId = "";//财务信息主键
var tokenJson = JSON.parse(decodeURIComponent(web.readCookie("loginData")));
var settleSectionOption = getBaseDataDictionaryFn2(20);//结账区间
$(".settleSection").html(settleSectionOption);
var settleDayOption = getBaseDataDictionaryFn(10);//结账时间
if(window.location.pathname.indexOf("commonDetailPage") > -1){
    // renderDetail();//详情信息渲染
    if (status != 1) {
        console.log(status);
        $(".provider-name").attr("disabled","disabled");
    }
    
    $(".next-step").remove();
    $(".last-step").remove();
    $(".cancleEditBtn").show();
}else {
    $(".cancleEditBtn").remove();
    $(".edit-provider-name-btn").remove();
    $("input[name='provider-name']").removeAttr("readonly");
    $(".invoiceProviderNumber").parent().parent().remove();
}
console.log(thisProviderId)
if(thisProviderId&&thisProviderId!=""){
    renderDetail();//详情信息渲染
    //获取发票信息
    findProviderInvoiceByPageFn(1);
}
$(".financial-form").Validform({
    tiptype: 2,
    callback: function (form) {
        saveFinancialInfo();
        return false;
    }
});
/*保存数据*/
function saveFinancialInfo(stepFn) {
    var params = {
        // "actualSettleAccountsWays": $("input[name='actualSettleAccountsWays']:checked").val(),//结账方式（40298-背靠背支付；40297-票到付款")）
        "settleType": $("input[name='settleType']:checked").val(),//结账方式（40298-背靠背支付；40297-票到付款")）
        "settleDay": $(".settleDay").val(),//结账时间
        "settleSection": $(".settleSection").val(),//结账区间
        "bankAccount": $(".bankAccount").val(),//开户行
        "bankAccountId": $(".bankAccount").attr("data-id"),//开户行id
        "bankAccountName": $(".bankAccountName").val(),//户名
        "bankAccountNumber": $(".bankAccountNumber").val(),//银行账号
        "createUserName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,//创建人
        "linkAccountNumber": $(".linkAccountNumber").val(),//联行号
        "providerId": thisProviderId,//服务商id
        "payWay": '0', //$("input[name='payWay']:checked").val(),//结算方式（0:企业转账,1:现金,2:承兑,3:部分承兑）
        "updateUserName":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,//修改人
        // "ticketDays": $(".ticketDays").val(),//票到几日
        "invoiceProviderName": $(".provider-name").val(),//开票服务商名称
    }
    var judgmentFieldObj = {
        // "actualSettleAccountsWays": "请选择结账方式",//结账方式（0:背靠背支付,1:票到几日付款）
        "settleType": "请选择付款方式",//结账方式（40298-背靠背支付；40297-票到付款")）
        "settleDay": "请选择结账时间",//结账时间
        "settleSection": "请选择结账区间",//结账区间
        "bankAccount": "请输入开户行",//开户行
        "bankAccountId": "请输入开户行",//开户行id
        "bankAccountName": "请输入户名",//户名
        "bankAccountNumber": "请输入银行账号",//银行账号
        "createUserName": "请输入创建人",//创建人
        "linkAccountNumber": "请输入联行号",//联行号
        "providerId": "请输入服务商id",//服务商id
        "payWay": "请选择结算方式",//结算方式（0:企业转账,1:现金,2:承兑,3:部分承兑）
        "updateUserName": "请输入修改人",//修改人
        "invoiceProviderName": "请输入开票服务商名称",//开票服务商名称
    }
    if(window.location.pathname.indexOf("commonDetailPage") > -1||financeHasData){
        var doUrl = root.approvedServiceProviders.updateProviderFinanceById;
        params.id = financeId
    }else {
        var doUrl = root.approvedServiceProviders.addProviderFinance;
    }
    var isContinue = nullValueJudgmentFn(params,judgmentFieldObj);
    if(!isContinue){
        return false;
    }
    /*else {
        if (params.actualSettleAccountsWays==1&&params.ticketDays==""){
            $.Huimodalalert("请选择实际结账时间",2000);
            return false;
        }
    }*/
    console.log(params)
    web.doAjax(doUrl, 'post',params, function (data) {
        if(data.code == 0){
            $.Huimodalalert(data.msg,2000);
            if(window.location.pathname.indexOf("commonDetailPage") > -1){
                $(".form-box").load("detailPackage/financialInfoDetail.html");
            }
            if(stepFn){
                console.log(stepFn)
                eval(stepFn)
            }
        }else {
            $.Huimodalalert(data.msg,2000);
        }
    },1);
}

/*财务信息*/
// 获取结账区间、结账时间
function getBaseDataDictionaryFn(type) {
    let optionStr = "";
    web.doAjax(root.approvedServiceProviders.getBaseDataDictionary, 'get', {type: type}, function (data) {

            if(data.code == 0){
                console.log($("input[name='settleType']:checked").val())
                data.data.forEach((item) => {
                    console.log(item.dictionaryId)
                    if($("input[name='settleType']:checked").val()=="40298" && item.dictionaryId=="40289"){
                        optionStr += "<option value='" + item.dictionaryId + "'>" + item.dictionaryValue +"</option>"
                    }else if($("input[name='settleType']:checked").val()=="40297"){
                        optionStr += "<option value='" + item.dictionaryId + "'>" + item.dictionaryValue +"</option>"

                    }
            });
            }else {
                $.Huimodalalert(data.msg,2000);
            }

    },2,false);
    $(".settleDay").html(optionStr);
    setSettleSectionFn()
}
function getBaseDataDictionaryFn2(type) {
    let optionStr = "";
    web.doAjax(root.approvedServiceProviders.getBaseDataDictionary, 'get', {type: type}, function (data) {

            if(data.code == 0){
                data.data.forEach((item) => {
                    if (item.dictionaryValue != 0) {
                        optionStr += "<option class='dictionaryOpton' value='" + item.dictionaryId + "'>" + item.dictionaryValue +"</option>"
                    }
            });
            }else {
                $.Huimodalalert(data.msg,2000);
            }

    },2,false);
    return optionStr;
}
function setSettleSectionFn() {
    if($(".settleDay").val() == "40289"){
        $(".settleSection").val(0).attr({"disabled": "disabled"});
        var optionStr = '<option value="1101">0</option>';
        $(".settleSection").html(optionStr);

    }else {
        $(".settleSection").removeAttr("disabled");
        var settleSectionOption = getBaseDataDictionaryFn2(20);//结账区间
        $(".settleSection").html(settleSectionOption);
    }
}
//获取财务信息
function renderDetail() {
    //获取详情信息
    var getFinancialDetail = getFinancialDetailPro(thisProviderId);
    getFinancialDetail.then(
        (res) => {
            if (res){
                renderForm(res);
                financeHasData = true;
            }else {
                financeHasData = false;
            }
        },  // 成功
        (err) => {console.log(err)} // 失败
    )
}
/*详情信息渲染*/
function renderForm(res){
    console.log(res)
    $("input[name='settleType'][value='"+res.settleType+"']").prop("checked",true);//结账方式（40298-背靠背支付；40297-票到付款")）
    $(".bankAccount").val(res.bankAccount);//开户行
    $(".bankAccount").attr("data-id",res.bankAccountId);//开户行
    $(".bankAccountName").val(res.bankAccountName);//户名
    $(".bankAccountNumber").val(res.bankAccountNumber);//银行账号
    $(".linkAccountNumber").val(res.linkAccountNumber);//联行号
    $(".provider-name").val(res.invoiceProviderName);
    $(".invoiceProviderNumber").html(res.invoiceProviderNumber);
    $("input[name='settleWay'][value='"+res.settleWay+"']").prop("checked",true);//结算方式（0:企业转账,1:现金,2:承兑,3:部分承兑）
    $(".ticketDays").val(res.ticketDays);//票到几日
    $("input[name='payWay'][value='"+res.payWay+"']").prop("checked",true);//结算方式（0:企业转账,1:现金,2:承兑,3:部分承兑）
    // $(".ticketDays").val(res.ticketDays);//票到几日
    $(".settleSection").val(res.settleSection);//结账区间
    financeId = res.id;
    getBaseDataDictionaryFn(10)
};

function findProviderInvoiceByPageFn(pageNum) {
    var params = {
        providerId: thisProviderId,
        pageSize: 10,
        pageNumber: pageNum,
    }
    web.doAjax(root.approvedServiceProviders.findProviderInvoiceByPage, 'post',params, function (data) {
        if(data.code == 0){
            console.log(data)
            $('.M-box3').pagination({
                pageCount:data.totalPage,
                current:pageNum,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    comPageNum = api.getCurrent();
                    findProviderInvoiceByPageFn(api.getCurrent());
                }
            });
            renderBillingTable(data.result);
        }else {
            $.Huimodalalert(data.msg,2000);
        }
    },2);
}
function renderBillingTable(data){
    var billingHtml = "";
    data.forEach((item,index) => {
        billingHtml += '<tr class="text-c">\n' +
            '                        <td>'+(index+1)+'</td>\n' +
            '                        <td title="'+item.companyName+'">'+item.companyName+'</td>\n' +
            '                        <td title="'+item.taxNo+'">'+item.taxNo+'</td>\n' +
            '                        <td title="'+item.address+'">'+item.address+'</td>\n' +
            '                        <td title="'+item.phone+'">'+item.phone+'</td>\n' +
            '                        <td title="'+item.bankAccount+'">'+item.bankAccount+'</td>\n' +
            '                        <td title="'+item.bankAccountNumber+'">'+item.bankAccountNumber+'</td>\n' +
            '                        <td><a class="mr-10" onclick="addBillingInfoFn('+item.id+')">修改</a><a onclick="deleteBillingFn('+item.id+')">删除</a></td>\n' +
            '                    </tr>';
    })
    $("#billingTable tbody").html(billingHtml);
}

/*新增或修改开票信息*/
function addBillingInfoFn(id) {
    if(id){
        var content = "addPackage/addBillingInfo.html?id="+id+"&providerId="+thisProviderId;
        var title = "修改开票信息"
    }else {
        var content = "addPackage/addBillingInfo.html?providerId="+thisProviderId;
        var title = "新增开票信息"
    }
    var index = layer.open({
        type: 2,
        title: title,
        content: content,
        area: ['655px', '432px'],
        offset: ['100px', '100px']
    });
}
/*删除开票信息*/
function deleteBillingFn(id) {
    layer.confirm('是否确认删除？',function (index) {
        var params = {
            id:id
        }
        web.doAjax(root.approvedServiceProviders.deteleProviderInvoiceById, 'post',params, function (data) {
            if(data.code == 0){
                $.Huimodalalert(data.msg,2000);
                findProviderInvoiceByPageFn(1);
                layer.close(index);
            }else {
                $.Huimodalalert(data.msg,2000);
            }
        },2);
    })

}
/*合作客户*/
function searchBankAccountFn(el,type) {
    if(type&&type=="inp"){
        $(el).attr("data-id","");
    }
    var params = {
        "bankName": el.value
    }
    web.doAjax(root.communalbase.getBankDocList,'post',params, function (data) {
        if(data.errorCode == "0") {
            $(".bankAccountList").css("display","block");
            var bankAccountHtml = '';
            if(!data.data.data||data.data.data.length == 0) {
                bankAccountHtml = '<li class="clearfix pl-10 mb-5">无数据</li>';
            } else {
                data.data.data.forEach((item) => {
                    bankAccountHtml += "<li class='clearfix pl-10 mb-5' onclick='selectBankAccountItem("+JSON.stringify(item)+")'>"+item.bankName+"</li>"
                })
            }
            $(".bankAccountList").html(bankAccountHtml);
        }
    },1);
}
function selectBankAccountItem(data) {
    $(".bankAccount").val(data.bankName).attr("data-id",data.bankId);
    $(".bankAccountList").hide();
}
$(document).bind("click", function(e) {
    if($(e.target).closest(".bankAccountList").length == 0 && $(e.target).closest(".bankAccount").length == 0){
        $(".bankAccountList").hide();
    }
});


// 关联弹框
function provider_Dame_Dialogs () {
    // $("input[name='channelImportantSkuId']").val(id);
    // $("input[name='relevance-skuCode']").val(skuCode);
    // $("#relevance-pro-info").html("");
    $('#normal').modal('show')
}

//修改开票服务商名称
function submit_Provider_Dame () {
    var invoiceProviderName = $("input[name='invoiceProviderName']").val();
    if (!invoiceProviderName) {
        $.Huimodalalert("开票服务商名称不能为空",2000);
        return false;
    }
    if (invoiceProviderName.length>50) {
        $.Huimodalalert("开票服务商名称最大长度不超过50个字符",2000);
        return false;
    }

    var json = {
        providerId: thisProviderId,
        invoiceProviderName: invoiceProviderName,
        operateUserId: tokenJson.user.user_ID,
        operateUserName: tokenJson.user.name,
    };

    $.ajax({
        url: root.approvedServiceProviders.updateInvoiceProvider,
        cache: false,  //禁用缓存
        type: "POST",
        processData: false,
        contentType: false,
        data: JSON.stringify(json),
        success: function (data) {
            if (!data) {
                $.Huimodalalert("更新开票服务商名称接口返回数据为" + data,2000);
                return false;
            }
            $.Huimodalalert(data.msg,2000);
            if (data.code == "0") {
                $(".invoiceProviderNumber").html(data.data.invoiceProviderNumber);
                $("input[name='provider-name']").val(data.data.invoiceProviderName);
                $('#normal').modal('hide');
            }
        },
    })
}
